package com.wind.util;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;

import java.util.Random;

/**
 * @ClassName TXSMSUtil
 * @Description Hey, it's compiled! Pack it!
 * @Author Administrator
 * @Date 2021/5/27 23:30
 * @Version 1.0
 */
public class TXSMSUtil {

    private static final int appId = 1400527529;

    private static final String appKey = "33a9734b55686c4f48dc7b0516b6b9d0";

    private static final int templateId = 973845;

    private static final String sign = "心口网络";

    public static String sendSMS(String phoneNumber) {
        String reStr = "";
        String code = getCode();
        try{
            String[] params = {code};
            SmsSingleSender smsSingleSender = new SmsSingleSender(appId, appKey);
            SmsSingleSenderResult result = smsSingleSender.sendWithParam("86", phoneNumber, templateId, params, sign, "", "");
            if(result.result == 0){
                RedisUtil.set(KeyPrefixConst.key_sms + phoneNumber, code, 5*60);
                reStr = "SUCCESS";
                System.out.println("发送成功");
            }else{
                reStr = result.errMsg;
                System.out.println("发送失败" + result.errMsg);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  reStr;
    }

    /**
     * 随机生成6位数字
     *
     * @return
     */
    public static String getCode() {
        String chars = "1234567890";
        String code = "";
        for (int i = 0; i < 6; i++) {
            Random r = new Random();
            code += chars.charAt(r.nextInt(chars.length() - 1));
        }
        return code;
    }

    /**
     * 获取短信验证码
     * @param phone
     * @return
     */
    public static String get(String phone) {
        Object coding = RedisUtil.get(KeyPrefixConst.key_sms+phone);
        String code = null == coding ? null : coding.toString();
        String failure = phone + "的短信登录验证码已失效";
        String success = phone + " 的短信登录验证码为 => " + code;
        System.out.println(null == code ? failure : success);
        return code;
    }

}
